package com.xiaojie.sharding.sphere.shardingalgorithm;

import com.google.common.collect.Range;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Map;

/**
 * @Description: 复合分片 分库算法
 * @author: yan
 * @date: 2022.03.12
 */
@Component
public class MyDBComplexShardingStrategy implements ComplexKeysShardingAlgorithm {

    @Override
    public Collection<String> doSharding(Collection availableTargetNames, ComplexKeysShardingValue shardingValue) {
        //分片的字段集合
        Map<String, Collection> columnMap = shardingValue.getColumnNameAndShardingValuesMap();
        //分片的范围规则
        Map<String, Range> rangeValuesMap = shardingValue.getColumnNameAndRangeValuesMap();
        //获取分片字段的集合
        Collection<Integer> agesColumn = columnMap.get("age");
        Collection<Long> idColumn = columnMap.get("id");
        ArrayList<String> list = new ArrayList();
        for (Integer age : agesColumn) {
            for (Long id : idColumn) {
                String suffix = null;
                if (age > 30) {
                    suffix = id % age % availableTargetNames.size() + "";
                } else {
                    suffix = (id + age) % availableTargetNames.size() + "";
                }
                for (Object db : availableTargetNames) {
                    String dbName = (String) db;
                    if (dbName.endsWith(suffix)) {
                        list.add(dbName);
                    }
                }
            }
        }
        return list;
    }
}
